"use strict";
define(function(require, exports, module) {
    var _public = module.exports = {};
    var $ = require('jquery'),
        common = require('lib/common'),
        template = require('lib/template'),
        report = require('business/report'),
        router = require('business/router');


    _public.init = function() {
    	//限制操作
    	console.log(_public.users);
    	if(_public.users.loginid!==_public.users.visiterid){
    		//hide
    	$(".dongtai-input").hide();
    	$(".send-btn").hide();
    		
    	}

        //add
        _public.getCourse();
        //end
        var $publisher = $('#publisher').change(function() {
            var $this = $(this).parents('form'),
                type = "type" + Math.ceil(Math.random() * 10000000000);
            $this.find('[name="type"]').val(type);
            $this.submit();

            window[type] = function(res) {
                if (res.status == "0") {
                    if (++$publisher.count > 3) {
                        alert('最多上传3个文件！');
                        return;
                    }
                    $('.publisher-photo').append('<img class="publisher-photo-item" src="' + res.data + '" alt="uploader"/>');
                } else {
                    console.log("send data");
                    console.log(res);
                    // alert(res.info);
                };
            }
        });
        //获取资源列表

        ;
        _public.getRemoteData("/faceb-cupt/resources/users/" + _public.users.visiterid, "POST", {}, function(res) {
            console.log("resourses");
            var res_container = $(".js-resource");
            var base_url = "/faceb-cupt/resources/download/"
            if (res && res.data.length > 0) {
                for (var i = 0, length = res.data.length; i < length; i++) {
                    var resTmp = res.data[i];
                    var res_a = $("<a>");
                    res_a.addClass('upload-item');
                    res_a.attr("href", base_url + resTmp["r_id"]);
                    res_a.text(resTmp["r_name"]);
                    res_container.append(res_a);
                }
            }
        });


        //获取资源列表
        $publisher.count = 0;

        $('#publisher-btn').click(function() {
            $publisher.trigger('click')
        })

        var $publisherSend = $('#publisher-send').click(function() {

        	var publicData={
               
            };
        	var editTxt=$('#editor').val();
        	if(editTxt.split("#").length==3){
        		publicData.content=$('#editor').val();
        		publicData.top=$('#editor').val().split("#")[1];

        	}else{
        		publicData.content=$('#editor').val();

        	}


        	

            
            $.post('/faceb-cupt/news/public', publicData).done(function(res) {
                var tempdata = JSON.parse(res);
                if (tempdata.status == "0") {
                    window.location.reload();
                } else {
                    alert("发表失败，请稍后再试");
                    cosnole.log(tempdata);
                }
            })
        })

        $('#uploader-file').change(function() {

            var userid = document.cookie.split("=")[1];
            $(".js-uploaduser").val(userid);
            $(this).parents('form').submit()
        });




        var user_id = _public.readCookie("userid");
        // console.log(user_id);
        var data = Date.now();
        $.ajax({
                url: '/faceb-cupt/news/users/' + user_id,
                dataType: "json",
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                type: 'POST',
                data: {},
            })
            .done(function(data) {
                console.log(data);
                console.log(data.status);
                if (data.status == "0") {
                    var container = $("#article-content");
                    common.template("article-me-tpl", data, container);

                    //add event
                    $(".js-godetail").on("click", function(e) {
                        var nid = $(this).data("nid");
                        window.location.href = "/faceb-cupt/tpl/news/detail/" + _public.users.visiterid + "?word=" + nid;
                    });

                    //edit like
                    var like_btn = $(".js-elike");
                    like_btn.on("click", function(e) {
                        if(!window.addlike){
                            window.addlike=true;
                            var nid = $(this).parents(".sub-plain").data("nid");
                            var btn_this=$(this);
                            $.ajax({
                                url: '/faceb-cupt/news/like/' + nid,
                                dataType: "json",
                                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                                type: 'POST',
                                data: {},
                            }).done(function(data) {
                                console.log("like test");
                                console.log(data);
                                if(data&&data.status=="0"){
                                   var edit_end=btn_this.data("like")+1;
                                   btn_this.text(edit_end+"喜欢");
                                   btn_this.data("like",edit_end);
                                }
                            });
                        }else{
                            window.addlike=true;
                        }
                        

                    });


                } else {
                    console.log(data.info);
                    alert("加载失败，请稍后再试！");
                }
            })
            .fail(function(data) {
                console.log("error");
            })
            .always(function(data) {
                console.log("complete");
            });



        //bindEvent
        var header_btn = $(".js-header");
        header_btn.on("click", function(e) {
            $(".personal-box").toggleClass('hide');
        });
        //goto course
        $(".go-course").on("click", function(e) {
            window.location.href = "/faceb-cupt/tpl/course/users/" + _public.users.visiterid;

        });
        //goto detail



        $(".js-logout").on("click", function(e) {
            console.log("hello");
            /*  _public.getRemoteData("/faceb-cupt/deallogout","GET", {}, function(){
                  window.location.href="/faceb-cupt/tpl/login";
              });*/
            $.get('/faceb-cupt/deallogout', function(data) {
                /*optional stuff to do after success */
                window.location.href = "/faceb-cupt/tpl/login";
            });

        });
        //gocenter
        var gocenter = $(".js-gocenter");
        gocenter.on("click", function(e) {
            window.location.reload();
        });





    };
    _public.readCookie = function(name) {
        var cookieValue = "";
        var search = name + "=";
        if (document.cookie.length > 0) {
            var offset = document.cookie.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                var end = document.cookie.indexOf(";", offset);
                if (end == -1)
                    end = document.cookie.length;
                cookieValue = unescape(document.cookie.substring(offset, end))
            }
        }
        return cookieValue;
    }
    _public.getRemoteData = function(url, method, data, callback) {
            //var result;
            $.ajax({
                type: method,
                url: url,
                data: data,
                dataType: "json"
            }).done(callback);

        },
        _public.users = {
            loginid: $(".js-loginid").data("id"),
            visiterid: $(".js-visitid").data("id")
        },
        _public.getCourse = function() {
            //获取当前星期几
        
            var date = new Date();
            var weekday = date.getDay();
            var weekArr=["星期天","星期一","星期二","星期三","星期四","星期五","星期六"];
            $(".js-week").text(weekArr[date.getDay()]);



            //获取整个课表
            var visiterid = _public.users.visiterid;
            //console.log("visiterid"+visiterid)
            var url = "/faceb-cupt/users/" + visiterid + "/courses";
            console.log(url);
            _public.getRemoteData(url, "post", {}, function(data) {
                if (data && data.status == "0") {
                    console.log("course data");
                    console.log(data);
                    var res = data.data;
                    var result = [];
                    res = JSON.parse(res["_1"]);
                    for (var item in res) {
                        var date_num = item.split("_")[1];
                        if (date_num == weekday) {
                            result.push(res[item].split(",")[0]);
                        }
                    }

                    //添加到页面     
                    var $course = $(".js-course");
                    for (var i = 0, length = $course.length; i < length; i++) {
                        $course.eq(i).text(result[i]);
                    }



                }
            });

        }
});
